import React, {
  createRef,
  useEffect,
  useState,
  useCallback,
  useRef,
} from "react";
import "./index.scss";
import classNames from "classnames";
interface Props {
  header?: React.ReactNode;
  children?: React.ReactNode;
}
export const Accordion = ({ header, children }: Props) => {
  const [open, setOpen] = useState(true);
  const containerRef = createRef<HTMLDivElement>();
  const titleRef = createRef<HTMLDivElement>();
  const maxHeight = useRef({ maxHeight: "0px" });
  useEffect(() => {
    if (!containerRef.current) return;
    // setTimeout(() => {
    const container = containerRef.current as HTMLDivElement;
    maxHeight.current.maxHeight = getComputedStyle(container).height;
    container.style.maxHeight = maxHeight.current.maxHeight;
    // });
  }, []);
  const handleToggle = useCallback(() => {
    setOpen(!open);
    const container = containerRef.current as HTMLDivElement;
    if (!container) return;
    const titleEle = titleRef.current as HTMLDivElement;
    if (open) {
      container.style.maxHeight = getComputedStyle(titleEle).height;
    } else {
      container.style.maxHeight = maxHeight.current.maxHeight;
    }
  }, [open, containerRef, titleRef]);
  return (
    <div
      className={classNames("drop-down-card", {
        close: !open,
      })}
      ref={containerRef}
    >
      <div className="title" ref={titleRef} onClick={handleToggle}>
        {header}
      </div>
      {children}
    </div>
  );
};
